package com.snow.springboot.task;

import com.snow.springboot.pojo.domain.DiagnoseInfo;
import com.snow.springboot.service.DiagnoseService;
import com.snow.springboot.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Package: com.snow.springboot.task
 * @ClassName: SaveDiagnoseInfoTask
 * @Description: 批量保存诊断书信息
 * @author: lurui
 * @Date: 2018/10/30 3:23 PM
 * @version:
 */
public class SaveDiagnoseInfoTask implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(SaveDiagnoseInfoTask.class);

    private DiagnoseService diagnoseService;

    private BlockingQueue<DiagnoseInfo> queue;

    public SaveDiagnoseInfoTask(DiagnoseService diagnoseService, BlockingQueue<DiagnoseInfo> queue) {
        this.diagnoseService = diagnoseService;
        this.queue = queue;
    }

    @Override
    public void run() {
        DiagnoseInfo diagnoseInfo = null;
        boolean flag = true;
        try {
            while (flag) {
                diagnoseInfo = queue.poll(60, TimeUnit.SECONDS);
                LOGGER.info("consume diagnose start!{}", diagnoseInfo.getDiagnoseId());
                if (diagnoseInfo != null) {
                    boolean result = diagnoseService.saveDiagnoseInfo(diagnoseInfo);
                    if (!result) {
                        FileUtil.writeByte("/Users/apple/Desktop/consumeId.txt", diagnoseInfo.getDiagnoseId());
                    }
                } else {
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("consumeDiagnose error:{}", diagnoseInfo.getDiagnoseId());
            FileUtil.writeByte("/Users/apple/Desktop/consumeId.txt", diagnoseInfo.getDiagnoseId());
            Thread.currentThread().interrupt();
        }
    }
}
